package com.jht.bletool.ui;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.cardview.widget.CardView;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;

import com.github.rahatarmanahmed.cpv.CircularProgressView;
import com.google.android.material.tabs.TabLayout;
import com.hjq.permissions.OnPermission;
import com.hjq.permissions.XXPermissions;
import com.hjq.xtoast.OnClickListener;
import com.hjq.xtoast.XToast;
import com.jht.bletool.BuildConfig;
import com.jht.bletool.R;
import com.jht.bletool.adapter.MyViewPageAdapter;
import com.jht.bletool.config.VersionChangeLog;
import com.jht.bletool.fragment.BleDevicesFragment;
import com.jht.bletool.fragment.ConnectedBleDevicesFragment;
import com.jht.bletool.util.DateUtil;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

import top.codestudy.lib_common_ui.splash.SplashActivity;

public class MainActivity extends BaseActivity {
    private static final String TAG = "MainActivity";

    private ListView lvAll;
    private ViewPager mVpMain;
    private TabLayout mTabLayout;
    private XToast show;
    private UiHandler uiHandler;
    private ImageView mIvMenu;
    private TextView mTvTitle;
    private CircularProgressView mProgressView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        isDeviceSupportBle();
        uiHandler = new UiHandler(this);
        Log.i(TAG, "onCreate: DateUtil.getCurrentTime() ==> " + DateUtil.getCurrentTime());

    }

    private void isDeviceSupportBle() {
        if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
            Toast.makeText(this, R.string.not_support_ble, Toast.LENGTH_SHORT).show();
            finish();
            return;
        }

    }

    private void initView() {
        mIvMenu = findViewById(R.id.iv_menu);
        mIvMenu.setBackground(getResources().getDrawable(R.drawable.icon_menu));
        mIvMenu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, AppSettingActivity.class);
                startActivity(intent);
            }
        });

        mTvTitle = findViewById(R.id.tv_title);
        mProgressView = findViewById(R.id.progress_view);

        mVpMain = findViewById(R.id.vp_main);
        mTabLayout = findViewById(R.id.tab_layout);
        initViewPage();
        mTabLayout.setupWithViewPager(mVpMain);

    }

    @Override
    protected void onStart() {
        super.onStart();
        initView();
    }

    @Override
    protected void onResume() {
        //getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
        super.onResume();
        initSettingDialog();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    private void initViewPage() {
        List<Fragment> fragments = initFragments();
        MyViewPageAdapter myViewPageAdapter = new MyViewPageAdapter(getSupportFragmentManager(), fragments);
        mVpMain.setAdapter(myViewPageAdapter);
    }

    private List<Fragment> initFragments() {
        BleDevicesFragment bleDevicesFragment = BleDevicesFragment.newInstance(getApplicationContext(), uiHandler);
        ConnectedBleDevicesFragment connectedBleDevicesFragment = ConnectedBleDevicesFragment.newInstance(getApplicationContext(), uiHandler);
        List<Fragment> data = new ArrayList<>();
        data.add(bleDevicesFragment);
        data.add(connectedBleDevicesFragment);
        return data;

    }

    private void requestPermissions() {
        XXPermissions.with(this)
                // 可设置被拒绝后继续申请，直到用户授权或者永久拒绝
                .constantRequest()
                // 支持请求6.0悬浮窗权限8.0请求安装权限
                //.permission(Permission.SYSTEM_ALERT_WINDOW, Permission.REQUEST_INSTALL_PACKAGES)
                // 不指定权限则自动获取清单中的危险权限
                // .permission(Permission.Group.STORAGE, Permission.Group.CALENDAR)
                .request(new OnPermission() {

                    @Override
                    public void hasPermission(List<String> granted, boolean all) {
                        if (!all) {

                            showGoAppSettingsDialog();
                        }
                    }

                    @Override
                    public void noPermission(List<String> denied, boolean quick) {
                        Log.i(TAG, "noPermission: " + denied + " ; " + quick);
                    }
                });
    }

    private void initSettingDialog() {
// 传入 Application 对象表示设置成全局的
        show = new XToast(MainActivity.this)
                .setView(R.layout.layout_go_setting_dialog)
                .setDuration(0)
                // 设置动画样式
                .setAnimStyle(R.style.go_setting_anim_style)
                .setOnClickListener(R.id.ll_setting_parent, new OnClickListener<LinearLayout>() {

                    @Override
                    public void onClick(XToast toast, LinearLayout view) {
                        // 点击这个 View 后消失
                        //toast.cancel();
                        Log.i(TAG, "onClick: 拦截事件用的，优化ue");
                        // 跳转到某个Activity
                        // toast.startActivity(intent);
                    }
                })
                .setOnClickListener(R.id.btn_go_setting, new OnClickListener<Button>() {
                    @Override
                    public void onClick(XToast toast, Button view) {
                        XXPermissions.gotoPermissionSettings(MainActivity.this);
                        toast.cancel();

                    }
                })
                .setOnClickListener(R.id.cd_content, new OnClickListener<CardView>() {
                    @Override
                    public void onClick(XToast toast, CardView view) {
                        Log.i(TAG, "onClick: 拦截事件用的，优化ue");
                    }
                });
    }

    private void showGoAppSettingsDialog() {

        show.show();
    }

    public void stopRotation() {
        mProgressView.setVisibility(View.INVISIBLE);
    }

    public void startRotation() {
        mProgressView.setVisibility(View.VISIBLE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.i(TAG, "onActivityResult: ");
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        Log.i(TAG, "onNewIntent: ");
    }

    @Override
    public void onConfigurationChanged(@NonNull Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
    }

    private static class UiHandler extends Handler {

        WeakReference<MainActivity> mainActivityWeakReference;

        public UiHandler(MainActivity activity) {
            mainActivityWeakReference = new WeakReference<MainActivity>(activity);
        }

        @Override
        public void handleMessage(@NonNull Message msg) {
            int code = msg.what;
            switch (code) {
                case UIKeyCode.UI_SHOW_GO_SETTING_DIALOG:
                    mainActivityWeakReference.get().showGoAppSettingsDialog();
                    break;
                case UIKeyCode.UI_STOP_ROTATION:
                    mainActivityWeakReference.get().stopRotation();
                    break;
                case UIKeyCode.UI_START_ROTATION:
                    mainActivityWeakReference.get().startRotation();
                    break;
                default:
                    break;
            }
        }
    }
}
